<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 物资申领确认
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container-right">
      <div class="handle-box">
        <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            label-width="20px"
        >
          <el-form-item label-width="20px">
            <el-select
                v-model="query.collegeId"
                filterable
                placeholder="请选择学院"
                @focus="getAllCollege()"
            >
              <el-option
                  v-for="item in options"
                  :key="item.sid"
                  :label="item.collegeName"
                  :value="item.sid"
                  :disabled="item.collegeName!=='全学院'? false:true"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
                v-model="query.majorId"
                filterable
                placeholder="请选择专业"
                @focus="getMajor()"
            >
              <el-option
                  v-for="item in optionsMajors"
                  :key="item.sid"
                  :label="item.majorName"
                  :value="item.sid"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
                v-model="query.className"
                filterable
                placeholder="请选择班级"
                @focus="getClassList()"
                style="width: 80%"
            >
              <el-option
                  v-for="item in classList"
                  :key="item.className"
                  :label="item.className"
                  :value="item.className"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
                v-model="query.studentName"
                placeholder="姓名"
                class="inline-input"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                v-model="query.studentId"
                placeholder="学号"
                class="inline-input"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
            >搜索
            </el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
                type="primary"
                icon="el-icon-circle-plus-outline"
                @click="handleAdd"
            >查询未领取物资
            </el-button
            >
          </el-form-item>
        </el-form>
        <el-divider/>
        <div class="paddy">
          <!--          <el-button type="primary" plain @click="checkStates()"-->
          <!--          >已申领-->
          <!--          </el-button-->
          <!--          >-->
          <!--          <el-button type="primary" plain @click="checkStatesTwo()"-->
          <!--          >已领取-->
          <!--          </el-button-->
          <!--          >-->
          <el-button
              class="btn"
              @click="handleExport"
          >
            <img style="width: 20px; display: inline"
                 src="../../assets/img/downlod.png"/>下载导出
          </el-button
          >
        </div>
        <el-divider/>
        <div>
          <el-table
              :data="tableData"
              border
              class="table"
              ref="multipleTable"
              header-cell-class-name="table-header"
              :span-method="objectSpanMethod"
          >
            <el-table-column label="序号" type="index" :index="indexMethod"/>
            <el-table-column
                :show-overflow-tooltip="true"
                :prop="item.prop"
                :label="item.label"
                v-for="item in prompt"
                :key="item.prop"
                align="center"
            >
            </el-table-column>
            <el-table-column label="物品样例" align="center">
              <template #default="scope">
                <p v-if="scope.row.goodsUrl!=null">
                       <span v-for="(item,index) in scope.row.goodsUrl.split(',')" :key="index">
                     <el-image style="display: inline-flex;padding: 10px;width: 30%;height: 10%"
                               class="table-td-thumb"
                               :src="item"
                               :preview-src-list="[item]"
                     ></el-image>
              </span>
                </p>
              </template>
            </el-table-column>
            <el-table-column label="签字领取凭证" align="center" v-if='showtable'>
              <template #default="scope">
                <p v-if="scope.row.filesUrl!=null">
                       <span v-for="(item,index) in scope.row.filesUrl.split(',')" :key="index">
                     <el-image style="display: inline-flex;padding: 10px;width: 30%;height: 10%"
                               class="table-td-thumb"
                               :src="item"
                               :preview-src-list="[item]"
                     ></el-image>
              </span>
                </p>
              </template>
            </el-table-column>
            <el-table-column>
              <el-table-column
                  label="操作"
                  width="180"
                  align="center"
                  fixed="right"
              >
                <template #default="scope">
                  <el-button
                      type="text"
                      icon="el-icon-edit"
                      @click="handleEdit(scope.row)"
                  >查看签字表
                  </el-button>
                  <el-button
                      type="text"
                      icon="el-icon-delete"
                      class="red"
                      @click="handleDelete(scope.$index, scope.row.sid)"
                  >删除
                  </el-button
                  >
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
                :currentPage="query.pageNum"
                :page-sizes="[10, 20, 40]"
                :page-size="query.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageTotal"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <div>
      <!-- 选择物品 -->
      <el-dialog
          title="物品选择"
          v-model="dialogVisible"
          width="55%"
          :before-close="handleClose"
      >
        <div>
          <el-form
              :inline="true"
              :model="form"
              ref="formRef"
              :rules="rules"
              class="demo-form-inline"
              label-width="40px"
          >
            <el-form-item style="display: inline" label="请输入学号进行查询可选物资" prop="studentId">
              <el-input
                  v-model="form.studentId"
                  placeholder="学号"
                  class="inline-input"
                  style="display: inline-flex"
              ></el-input>
            </el-form-item>
            <el-form-item style="display: inline">
              <el-button
                  type="primary"
                  icon="el-icon-circle-plus-outline"
                  @click="getReceiveData"
              >筛选
              </el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <el-divider/>
        <div>
          <el-table
              :data="tableReceiveData"
              border
              class="table"
              ref="multipleTable"
              header-cell-class-name="table-header"
              @selection-change="handleSelectionChange"
              @row-click="clickRow"
          >
            <!--          <el-table-column label="序号" type="index" :index="indexMethod" />-->
            <el-table-column type="selection"/>
            <el-table-column
                :show-overflow-tooltip="true"
                :prop="item.prop"
                :label="item.label"
                v-for="item in propt"
                :key="item.prop"
                align="center"
            >
            </el-table-column>
            <el-table-column label="物品样例" align="center">
              <template #default="scope">
                <p v-if="scope.row.goodsUrl!=null">
                       <span v-for="(item,index) in scope.row.goodsUrl.split(',')" :key="index">
                     <el-image style="display: inline-flex;padding: 10px;width: 30%;height: 10%"
                               class="table-td-thumb"
                               :src="item"
                               :preview-src-list="[item]"
                     ></el-image>
              </span>
                </p>
              </template>
            </el-table-column>
          </el-table>

        </div>
        <el-divider/>
        <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">关闭</el-button>
              <!--               <el-button @click="checkReceive">选取</el-button>-->
            </span>
        </template>
      </el-dialog>
    </div>

    <div>
      <!-- 确认领取 -->
      <el-dialog
          title="确认领取登记"
          v-model="importVisible"
          width="55%"
          :before-close="handleClose">
        <div>
          <el-form ref="formRef" :rules="rules" :model="formReceive" label-width="80px">
            <el-form-item label="物品名称" prop="goodsName">
              <el-input v-model="formReceive.goodsName" aria-required="true" disabled
                        style="font-size: 35px;--el-avatar-font-color: #f02d2d"></el-input>
            </el-form-item>
            <el-form-item label="领取时间">
              <el-input v-model="formReceive.createTime" aria-required="true" disabled
                        style="font-size: 35px"></el-input>
            </el-form-item>
            <el-form-item label="学生姓名">
              <el-input v-model="formReceive.studentName" aria-required="true" disabled
                        style="font-size: 35px"></el-input>
            </el-form-item>
            <el-form-item label="学生学号">
              <el-input v-model="formReceive.studentId" aria-required="true" disabled
                        style="font-size: 35px"></el-input>
            </el-form-item>
            <!--             :file-list="fileList"-->
            <el-form-item label="领取确认表">
              <p v-if="formReceive.filesUrl!=null">
                <!--                       <span v-for="(item,index) in scope.row.roomurl.split(',')" :key="index">-->
                <el-image style="display: inline-flex;padding: 10px;width: 60%;height: 80%"
                          class="table-td-thumb"
                          :src="formReceive.filesUrl"
                          :preview-src-list="[formReceive.filesUrl]"
                ></el-image>
                <!--              </span>-->
              </p>


              <!--              <el-upload ref="pictureUpload" action="#" list-type="picture-card"-->
              <!--                         :limit="4" :on-exceed="handleExceed"-->
              <!--                         :auto-upload="false"-->
              <!--                         :file-list="fileList"-->
              <!--                         :on-change="handleFile">-->
              <!--                <template #default>-->
              <!--                  <i class="el-icon-plus"></i>-->

              <!--                </template>-->
              <!--                <template #file="{ file }">-->
              <!--                  <div>-->
              <!--                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>-->
              <!--                    <span class="el-upload-list__item-actions">-->
              <!--          <span-->
              <!--              v-if="!disabled"-->
              <!--              class="el-upload-list__item-delete"-->
              <!--              @click="handleRemove(file)"-->
              <!--          >-->
              <!--            <i class="el-icon-delete"></i>-->
              <!--          </span>-->
              <!--        </span>-->
              <!--                  </div>-->
              <!--                </template>-->
              <!--              </el-upload>-->
            </el-form-item>
          </el-form>
        </div>
        <el-divider/>
        <template #footer>
            <span class="dialog-footer">
              <el-button @click="importVisible = false">关闭</el-button>
              <!--               <el-button type="primary" @click="onSubmit">提交</el-button>-->
            </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import request from "../../utils/request";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";

export default {
  name: "ApplyReceive",
  methods: {
    // 行合并
// 参数分别是，行数据，列，行号，列号
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      const arr = this.tableData
      let rowspan = 1
      let colspan = 1
      // 要合并的列数，这个可以看需求自己定制
      const spanColumn = [0, 1, 2, 3, 4, 5]
      // 如果是要合并的行
      if (spanColumn.includes(columnIndex)) {
        // 遍历，如果有相同就加1，这里事先让后端把相同的放一起
        for (let i = rowIndex + 1; i < arr.length; i++) {
          // phid相同的合并，这里根据需求判断字段
          if (row.studentId === arr[i].studentId) {
            rowspan++
          } else {
            break
          }
        }
        // 如果行号大于0，判断phid等于当前行的上一行就是00 这里的逻辑666
        if (rowIndex > 0 && row.studentId === arr[rowIndex - 1].studentId) {
          rowspan = 0
          colspan = 0
        }
      }
      // 最后就是返回
      return {
        rowspan: rowspan,
        colspan: colspan,
      }
    },
    clickRow(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    //文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    //文件数量控制
    handleExceed(files, fileList) {
      console.log(fileList)
      this.$message.warning(
          `The limit is 1, you selected ${
              files.length
          } files this time, add up to ${files.length + fileList.length} totally`
      );
    },
    //文件移除
    handleRemove(file) {
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (var i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['url'] == file.url) {
          uploadFiles.splice(i, 1)
          this.fileList.splice(i, 1)
          console.log(this.fileList)
        }
      }
    },
  },

  setup() {
    const router = useRouter();
    const propt = [
      {label: "物品名称", prop: "goodsName"},
      {label: "物品类型", prop: "goodsType"},
    ];
    const prompt = [
      {label: "学生学号", prop: "studentId"},
      {label: "学生姓名", prop: "studentName"},
      {label: "学院", prop: "collegeName"},
      {label: "专业", prop: "majorName"},
      {label: "班级", prop: "className"},
      {label: "物品名称", prop: "goodsName"},
      {label: "物品类型", prop: "goodsType"},
      // {label: "领取确认状态", prop: "receiveStatus"},
    ];
    const query = reactive({
      collegeId: "",
      majorId: "",
      className: "",
      studentName: "",
      studentId: "",
      receiveStatus: "1",
      pageNum: 1,
      pageSize: 10,
    });
    const optionsMajors = ref([]);
    const getMajor = () => {
      request
          .get("/major/queryList", {
            params: {collegeId: query.collegeId, type: 1},
          })
          .then((res) => {
            optionsMajors.value = res.data;
          });
    };
    //班级下拉框
    const classList = ref([]);
    const getClassList = () => {
      classList.value = []
      request
          .get("/class/byMajorIdOrCollegeId", {
            params: {majorId: query.majorId},
          })
          .then((res) => {
            if (res.code !== "0") {
              ElMessage.warning(res.msg);
            } else {
              classList.value = res.data;
            }

          });
    };
    const tableData = ref([]);
    const pageTotal = ref(0);
    const dialogVisible = ref(false)
    const showtable = ref(false)

    // 获取表格数据
    const getData = () => {
      tableData.value = [];
      request
          .get("/receive/queryReceiveGoodsStudentVo", {
            params: query,
          })
          .then((res) => {
            if (res.code != 0) {
              ElMessage.warning(res.msg);
              tableData.value = [];
            } else {
              tableData.value = res.data.records;
              pageTotal.value = res.data.total;
              for (var i = 0; i < tableData.value.length; i++) {
                if (tableData.value[i].receiveStatus === 0) {
                  tableData.value[i].receiveStatus = "已经审领"
                }
                if (tableData.value[i].receiveStatus === 1) {
                  tableData.value[i].receiveStatus = "已领取"
                }
              }
            }
          });
    };
    getData();
    // const checkStates = () => {
    //   showtable.value = false
    //   query.receiveStatus = 0;
    //   getData();
    // };
    //
    // const checkStatesTwo = () => {
    //   query.receiveStatus = 1;
    //   showtable.value = true
    //   getData();
    // };
    // 查询操作
    const handleSearch = () => {
      query.pageNum = 1;
      getData();
    };
    // 分页大小
    const handleSizeChange = (val) => {
      query.pageSize = val;
      getData();
    };
    // 分页导航
    const handlePageChange = (val) => {
      query.pageNum = val;
      getData();
    };
    const indexMethod = (index, number) => {
      return (index + 1)
    };
    // 删除操作
    const handleDelete = (index, sid) => {
      console.log(sid)
      // 二次确认删除
      ElMessageBox.confirm("确定要 删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        request.delete("/receive/delete/" + sid).then((res) => {
          if (!res.data) {
            ElMessage.success("删除成功");
            tableData.value.splice(index, 1);
            getData()
          } else {
            ElMessage.error("删除失败");
          }
        });
      })
          .catch(() => {
          });
    };

    const tableReceiveData = ref([]);
    // 获取表格数据
    const getReceiveData = () => {
      tableReceiveData.value = []
      // 表单校验
      formRef.value.validate((valid) => {
        if (valid) {
          var studentId = form.studentId
          request
              .get("/goods/queryGoods/" + studentId)
              .then((res) => {
                if (res.code !== 0) {
                  ElMessage.warning(res.msg);
                } else {
                  if (res.data.length == 0) {
                    ElMessage.info("该学生以已经物品已经全部申领");
                  }
                }

                tableReceiveData.value = res.data;
              });
        } else {
          return false;
        }
      });
    };
    const handleAdd = () => {
      tableReceiveData.value = []
      form.studentId = ""
      dialogVisible.value = true;

    };
    const formRef = ref(null);
    const rules = {
      studentId: [{required: true, message: "学号必填参数", trigger: "blur"}],
    };
    const form = reactive({
      studentId: ""
    });
    //多选
    const tableSelection = reactive({
      idList: [],
      studentId: "",
    });
    //选择列表框
    const handleSelectionChange = (val) => {
      tableSelection.idList = [];
      for (var i in val) {
        tableSelection.idList.push(val[i].sid);
      }
    };

    const checkReceive = () => {
      console.log(tableSelection)
      tableSelection.studentId = form.studentId
      if (tableSelection.idList.length === 0) {
        ElMessage.info("请选择物品");
        return;
      }
      ElMessageBox.confirm("确定选择物品吗？", "提示", {
        type: "warning",
      }).then(() => {
            request
                .post("/receive/insertReceives", tableSelection)
                .then((res) => {
                  if (res.code === null) {
                    ElMessage.success("成功");
                    dialogVisible.value = false;
                    getData();
                  } else {
                    tableSelection.idList = [];
                    ElMessage.error(res.msg);
                  }
                });
          }
      );
    };
    //文件上传
    const disabled = ref(false)
    const importVisible = ref(false)
    const formData = new FormData();
    const root = "/receive/";
    const fileList = ref([]);
    const formReceive = reactive({
      goodsName: "",
      goodsId: "",
      sid: "",
      filesUrl: "",
      createTime: "",
      studentId: "",
      studentName: "",
    });
    const handleEdit = (row) => {
      console.log(row + "2222")
      importVisible.value = true
      formReceive.goodsName = row.goodsName
      formReceive.goodsId = row.goodsId
      formReceive.sid = row.sid
      formReceive.filesUrl = row.filesUrl
      formReceive.createTime = row.createTime
      formReceive.studentId = row.studentId
      formReceive.studentName = row.studentName
      // handleGetReceive(row.sid)
    };
    const handleGetReceive = (sid) => {
      fileList.value = []
      request.get(root + sid).then((res) => {
        var tadate = [];
        tadate = res.data.filesUrl.split(',')
        console.log(tadate.length)
        for (var i = 0; i < tadate.length; i++) {
          var file = {
            url: ""
          }
          file.url = tadate[i]
          if (file.url != null && file.url.length > 0) {
            fileList.value.push(file)
          }
        }
        console.log(fileList.value)
      });
    };
    const handleFile = (file, fileList) => {
      console.log(fileList)
      formData.delete("files")
      for (var i = 0; i < fileList.length; i++) {
        console.log(fileList[i])
        formData.append("files", fileList[i].raw);
      }
      // console.log(formData.getAll("files"))
    };
    // 提交
    const onSubmit = () => {
      formData.delete("sid");
      formData.append("sid", formReceive.sid);
      // formData.append("goodsId", formReceive.goodsId);
      console.log(fileList.value.length)
      console.log(formData)
      if (formReceive.sid) {
        if (fileList.value != null && fileList.value.length > 0) {
          for (var i = 0; i < fileList.value.length; i++) {
            formData.append("urls", fileList.value[i].url);
          }
        }
        request.post("/receive/updateOrinsertReceive", formData, {
          headers: {"Content-Type": "multipart/form-data"},
        }).then((res) => {
          if (res.code !== null) {
            ElMessage.error(res.msg);
          } else {
            ElMessage.success("提交成功！");
            formData.delete("sid");
            formData.delete("files");
            handleGetReceive(formReceive.sid)
            importVisible.value = false

            // formData.delete("goodsId");
          }
        });
      }
    };
    //学院下拉框
    const options = ref([]);
    const getAllCollege = () => {
      console.log(query.collegeId);
      request.get("/college/getAllCollege").then((res) => {
        options.value = res.data;
      });
    };
    //下载excel
    const handleExport = () => {
      console.log(query.receiveStatus)
      if (query.receiveStatus == null) {
        ElMessage.warning("导出文件的数据状态必选");
        return null
      }
      window.location.href =
          "http://localhost:9998/receive/statisticsExport?" +
          "receiveStatus=" +
          query.receiveStatus +
          " &majorId=" +
          query.majorId +
          "&className=" +
          query.className +
          "&studentName=" +
          query.studentName +
          "&studentId=" +
          query.studentId +
          "";
    };
    return {
      showtable,
      prompt,
      query,
      propt,
      form,
      optionsMajors,
      tableData,
      pageTotal,
      classList,
      indexMethod,
      // checkStates,
      // checkStatesTwo,
      getAllCollege, options,
      dialogVisible,
      tableReceiveData,
      rules,
      formRef,
      formReceive,
      tableSelection,
      handleSelectionChange,
      getReceiveData,
      checkReceive,
      fileList,
      getClassList,
      handleSearch,
      handleSizeChange,
      handlePageChange,
      handleDelete,
      handleAdd,
      handleGetReceive,
      handleEdit,
      handleExport,
      disabled,
      importVisible,
      handleFile,
      onSubmit,
      formData,
      getMajor,
    };
  }
}
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.exportStudent {
  display: inline-flex;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.paddy {
  display: flex;
  padding-top: 20px;
}
</style>